package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;


    @GetMapping("/category/list")
    public ResultInfo findList(){
       List<Category> list = null;
       //先查询缓存
       String categoryKey = "category_list";
       if(redisTemplate.hasKey(categoryKey)){
            list = (List<Category>) redisTemplate.opsForValue().get(categoryKey);
            log.info("查询redis缓存");
       }else {
           list = categoryService.findAll();
           log.info("查询MySQL数据库");
           //同步到redis中
           redisTemplate.opsForValue().set(categoryKey,list);
       }
       return ResultInfo.success(list);
    }

}
